package com.ossdemo.strategy.impl;

import com.ossdemo.exception.ServiceException;
import com.ossdemo.strategy.UploadStrategy;
import com.ossdemo.utils.FileUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

@Service
public abstract class AbstractUploadStrategyImpl implements UploadStrategy {
    @Override
    public String uploadFile(MultipartFile file, String path) {
        try {
            // 获取文件md5值
            String md5 = FileUtils.getMd5(file.getInputStream());
            // 获取文件扩展名
            String extName = FileUtils.getExtension(file);
            // 重新生成文件名
            String fileName = md5 + "." + extName;
            // 判断文件是否已存在
            String PATH = (path + fileName).substring(1);
            if (!exists(PATH)) {
                // 不存在则继续上传
                upload(path.substring(1), fileName, file.getInputStream());
            }
            // 返回文件访问路径
            return getFileAccessUrl(path + fileName);
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException("文件上传失败");
        }
    }

    @Override
    public List<String> getPhoto(String path) {
        return getAllPicture(path);
    }
    /**
     * 删除图片
     * @param path 图片地址
     * @return true 删除成功 false 删除失败
     */
    @Override
    public boolean deletePictureByUrl(String path) {
        return deletePicture(path);
    }

    /**
     * 判断文件是否存在
     *
     * @param filePath 文件路径
     * @return {@link Boolean}
     */
    public abstract Boolean exists(String filePath);

    /**
     * 上传
     *
     * @param path        路径
     * @param fileName    文件名
     * @param inputStream 输入流
     * @throws IOException io异常
     */
    public abstract void upload(String path, String fileName, InputStream inputStream) throws IOException;

    /**
     * 获取文件访问url
     *
     * @param filePath 文件路径
     * @return {@link String} 文件url
     */

    public abstract String getFileAccessUrl(String filePath);


    public abstract List<String> getAllPicture(String path);

    public abstract boolean deletePicture(String path);
}
